﻿using System.Collections.Generic;

namespace Framework
{
    public static class ResCache
    {
        private static LinkedList<Resource> _ResourceList = new LinkedList<Resource>();

        public static Resource Get(string url, int loadType)
        {
            Resource resource = Find(url);
            if (resource == null)
            {
                resource = new Resource(url, loadType);
                _ResourceList.AddLast(resource);
            }
            return resource;
        }

        public static void Remove(string url)
        {
            Resource resource = Find(url);
            if (resource != null && resource.IsUnused())
            {
                resource.Dispose();
                _ResourceList.Remove(resource);
            }
        }

        public static Resource Find(string url)
        {
            LinkedListNode<Resource> node = _ResourceList.First;
            while (node != null)
            {
                if (node.Value.url == url)
                {
                    return node.Value;
                }
                node = node.Next;
            }
            return null;
        }

        public static void RemoveUnused()
        {
            LinkedListNode<Resource> node = _ResourceList.First;
            while (node != null)
            {
                LinkedListNode<Resource> currentNode = node;
                node = node.Next;
                if (currentNode.Value.IsUnused())
                {
                    currentNode.Value.Dispose();
                    _ResourceList.Remove(currentNode);
                }
            }
        }

        public static void RemoveAll()
        {
            LinkedListNode<Resource> node = _ResourceList.First;
            while (node != null)
            {
                node.Value.Dispose();
                node = node.Next;
            }
            _ResourceList.Clear();
        }
    }
}